package com.example.sunran.controller;


import com.example.sunran.dao.PathMapper;
import com.example.sunran.dataobject.Path;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class MainController {

    @Autowired
    PathMapper pathMapper;

    static {
        File file = new File("./UploadFile");
        if (!file.exists()) {
            file.mkdirs();
        }
    }
    @GetMapping("/")
    public String index(){
        return "index";
    }

    @GetMapping("files")
    @ResponseBody
    public List<Path> getFileList(@RequestParam("path") String path){
        List<Path> paths = pathMapper.query(path);
        System.out.println(path);
        return paths;
    }

    @PostMapping("folder")
    @ResponseBody
    public String addFolder(@RequestParam("folderName")String name,@RequestParam("parent") String parent){
        Path path = new Path();
        path.setIsFolder(true);
        path.setName(name);
        path.setParent(parent);
        pathMapper.insert(path);
        return "ok";
    }

    @PostMapping("files")
    @ResponseBody
    public String addFile(@RequestParam("file") MultipartFile file, @RequestParam("parent")String parent) throws IOException {
        System.out.println(file.getOriginalFilename());

        //存储到UploadFile文件夹
        File saveFile = new File("./UploadFile/"+file.getOriginalFilename());
        if (!saveFile.exists()) {
            saveFile.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(saveFile);
        InputStream is = file.getInputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = is.read(b)) != -1) {
            fos.write(b,0,len);
        }
        fos.flush();
        fos.close();

        //存储到数据库
        Path path = new Path();
        path.setIsFolder(false);
        path.setName(file.getOriginalFilename());
        path.setParent(parent);
        pathMapper.insert(path);
        return "ok";
    }
}
